package com.zingrow.common.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zingrow.common.utils.PropertiesCommonUtil;
import com.zingrow.common.utils.StringUtil;

@SuppressWarnings("unused")
public class SetAllowFilter implements Filter {

    public static final String ALLOW_TAG = "allow_tag";

    private Map<String, String> map = new HashMap<String, String>();
    private Map<String, String> suffixmap = new HashMap<String, String>();

    private String hippourlsuffix = "";
    private String mobilesuffix = "";
    private String webservicesuffix = "";
    private String guidancesuffix = "";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        /**
         * 获取过滤不用进行拦截的URL
         */
        Properties properties = PropertiesCommonUtil.readPropertiesFile("/properties/sessionfilter.properties");
        String allowUrls = properties.getProperty("allowUrls");
        String suffixs = properties.getProperty("suffix");
        if (allowUrls != null) {
            String[] st = allowUrls.split(",");
            map.clear();
            for (String s : st) {
                map.put(s, s);
            }
        }
        if (suffixs != null) {
            String[] str = suffixs.split(",");
            suffixmap.clear();
            for (String s : str) {
                suffixmap.put(s, s);
            }
        }

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String contextPath = httpRequest.getContextPath();
        String requestUrl = httpRequest.getRequestURI().replace(contextPath, "");

        // 当遇到不须过滤的直接跳过,
        if ("/".equals(requestUrl) || requestUrl.contains("//")
                || map.get(StringUtil.parseSuffix(requestUrl, "url")) != null
                || suffixmap.get(StringUtil.parseSuffix(requestUrl, "suffix")) != null) {

            // 可以跳过
            request.setAttribute(ALLOW_TAG, true);

        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}
